package logic

import (
	"base/baserpc/baserpc"
	"base/baserpc/internal/svc"
	"base/cache"
	"base/models/mysql"
	"context"
	"github.com/zeromicro/go-zero/core/jsonx"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LimitLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLimitLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LimitLogic {
	return &LimitLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 分页
func (l *LimitLogic) Limit(in *baserpc.LimitRequest) (*baserpc.LimitResponse, error) {
	// todo: add your logic here and delete this line
	var note mysql.Note
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	result, _ := cache.Rdb.Get(l.ctx, "limt").Result()
	if result == "" {
		mysql.DB.Debug().Offset(int(offset)).Where("title like ?", "%"+in.Title+"%").Order("note_id desc").Find(&note)
		marshal, _ := jsonx.Marshal(&note)
		cache.Rdb.Set(l.ctx, "limit", marshal, time.Hour*2)
	}

	var LimitList []*baserpc.LimitList
	for _, _ = range LimitList {
		list := baserpc.LimitList{
			Title:   note.Title,
			Address: note.Address,
			Noteid:  int64(note.NoteId),
		}
		_ = append(LimitList, &list)
	}
	return &baserpc.LimitResponse{
		List: LimitList,
	}, nil
}
